<template>
  <div class="form-text">
    <input
      type="text"
      :value="value"
      @compositionstart="compositionstart"
      @compositionend="compositionend"
      @input="inputEvent"
      @focus="handlerInputFocus"
      @blur="handlerInputBlur"
      :placeholder="placeholder || placeholderText()"
      :maxlength="field.maxlength ? field.maxlength : maxlength"
      :id="`form_${field.fieldName}`" 
      autocomplete="off"
      :disabled="disabled"
    />
  </div>
</template>

<script>
import FormMixin from '@src/component/form/mixin/form';
import { FORM_FIELD_TEXT_MAX_LENGTH } from '@src/model/const/Number.ts';
import { genPlaceholder} from '../../util'

const IS_NUMBER_REG = /^\d{1,}$/

export default {
  name: 'form-text',
  mixins: [FormMixin],
  props: {
    value: {
      type: String,
      default: ''
    },
    isOnlyNumber: {
      type: Boolean,
      default: false
    },
    isNotInputZh: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
    }
  },
  data() {
    return {
      // 是否是输入中文
      $isInputZh: false,
      // placeholderText: ''
    }
  },
  watch: {
    field: {
      handler(newValue) {
        // this.placeholderText = genPlaceholder(this.field);
      },
      immediate: true
    }
  },
  computed: {
    maxlength() {
      if (this.field?.setting?.isLimitWord) {
        const max = this.field.setting.limitWordMax
        if (max) return max
      }
      return FORM_FIELD_TEXT_MAX_LENGTH
    },
  },
  methods: {
    placeholderText() {
      if (this.field?.setting?.isLimitWord) {
        this.field.maxlength = this.maxlength;
      }
      return genPlaceholder(this.field) ?? '';
    },
    /* 输入文字之前 */
    compositionstart(event) {
      this.$data.$isInputZh = true;
    },
    /* 输入文字之后 */
    compositionend(event) {
      
      if (!this.isNotInputZh) {
        this.$data.$isInputZh = false;
      }
      
      this.input(event);
    },
    inputEvent(event) {
      const eventValue = event.target.value
      
      if (this.isOnlyNumber && !IS_NUMBER_REG.test(eventValue)) {
        event.target.value = this.value
      }
      
      if (this.isOnlyNumber && !eventValue) {
        event.target.value = eventValue
      }
      
      // 如果是在中文输入 return
      if(this.$data.$isInputZh) return
      
      this.input(event);
    },
    handlerInputFocus() {
      this.$emit('focus')
    },
    handlerInputBlur() {
      this.$emit('blur', 'input')
    }
  },
}
</script>

<style lang="scss">
.form-text{
  width: 100%;

  input{
    width: 100%;
    &:disabled{
      -webkit-text-fill-color: #BFBFBF;
      border-color: #D9D9D9;
      background-color:#f5f5f5!important;
      &:hover{
        border-color: #D9D9D9;
      }
    }
  }
}
</style>
